<?php
class LogCommand extends CConsoleCommand {

	private $tempFile;
	private $lastDateDat;

	public function actionIndex($type, $limit = 5) {
		//		echo time();
	}
	public function init() {
		set_time_limit(0);
		$temp_folder = Yii :: getPathOfAlias("application.runtime.log.analyze");
		$this->ensureDirectory($temp_folder);
		$this->tempFile = $temp_folder . '/' . time();
		if(file_exists($this->tempFile ))
			@unlink($this->tempFile );
		$this->lastDateDat = Yii :: getPathOfAlias("application.config.last").'.dat';
	}

	/**
	 * @date 20110405130000
	 */
	public function actionAnalyze($file, $date = null) {
		if ($date === null) {
			$date = date('YmdHis', strtotime('-1 hours'));
		}
		$last = @file_get_contents($this->lastDateDat);
		$now = time();
		
		$date_fillter =  date('Y');
		if(empty($last)){
			$this->filterLog($file,$date_fillter);
		}else{
			
			$current = date('YmdH',$last);
			
			while($current < date('YmdH',$now) ){
				$date_fillter =  date('d/M/Y:H',strtotime("{$current}0000"));//, strtotime('-1 hours'));//'06/Apr/2011:13';
				$this->filterLog($file,$date_fillter);
				$current = date('YmdH',strtotime("+1 hours {$current}0000"));
				
			}
			
			
		}
		//store the last time.
		file_put_contents($this->lastDateDat,$now);
		
		$this->save2db();
		Yii::log("Log analyzed for $date_fillter .",CLogger::LEVEL_INFO,'LogCommand.actionAnalyze');
	}
	private function filterLog($file , $date_fillter){
		$command = 'cat ' . $file . ' |grep -i "' . $date_fillter . '"  ' .
		'|grep  -i "GET \/\w\{3,\} \{1\}"  ' .
		'|grep -i "HTTP\/1.1"" | 200" >> ' . $this->tempFile;  
		$handle = popen($command, 'r');

		$read = fread($handle, 2096);
		if (strlen($read) > 0) {
			throw new Exception('Errors.');
		}
		pclose($handle);
	}

	private function save2db() {
		
//		$counter = array();
		$handle = @fopen($this->tempFile, "r");

		if ($handle) {
			while (!feof($handle)) {
				$row = fgets($handle);
				$row = preg_replace('/[\[\]\"]+/', '', $row);
//								echo $row;
	
				$arr = explode("|", $row);
//				print_r($arr);
				if (count($arr) == 9) {
					$ip = trim($arr[0]);
					$time = strtotime($arr[2]);
					$today = date('Ymd', $time);
					$hour = date('H', $time);

					$domain = substr($arr[3], strpos($arr[3], '/') + 1);
					$domain = substr($domain, 0, strpos($domain, ' '));
					$domain = strtolower($domain);
					/*
					 * 屏除同一小时内的多次访问.
					 * 该功能已删除.
					 */
//					if(isset($counter[$ip.$domain])){
//						continue;	
//					}
//					
//					$counter[$ip.$domain]= 1;
					
					//views
					$model = ViewStatistic :: model();

					$result = $model->getCollection()->update(array (
								'domain' => $domain,
								'date' => $today
							), array (
								'$set' => array (
									'domain' => $domain,
									'date' => $today,
									'update' => time()
								),
								'$inc' => array (
									'views' => 1,
									"hours.{$hour}" => 1
								),
								
							), array (
							'upsert' => true,
						
					));
					
					//linked in
					$refer = $arr[6];
					if(strlen($refer)>6){
//						$linked_domain = substr($refer,strpos($refer,'//')+2);
//					 	$linked_domain = substr($linked_domain,0,strpos($linked_domain,'/'));
//					 	$linked_domain =$refer;
					 	$result = LogCommandHelper::parseReferer($refer);
					 	
					 	$refer = $result['url'];
//					 	print_r($result);
					 	if($result['isEngine']){//save in EngineKeywordStatistic
					 		
					 		$keywords = $result['keywords'];
					 		$host = str_replace('.','_',$result['host']);
					 		foreach($keywords as $keyword){

					 			
					 			$set =  array (
											'domain' => $domain,
						 					'keyword' => $keyword,
										);
										
								EngineKeywordStatistic::model()->getCollection()->update(array (
											'domain' => $domain,
						 					'keyword' => $keyword
										), array (
											'$set' =>$set,
											'$inc' => array (
												'count' => 1,
												"hosts.{$host}" => 1,
											),
											
										), array (
										'upsert' => true,
									
								));
					 		}
						 	
					 	}else{
					 		
						 	$set =  array (
											'domain' => $domain,
						 					'refer' => $refer,
											'update' => time()
										);
										
							LinkStatistic::model()->getCollection()->update(array (
										'domain' => $domain,
						 				'refer' => $refer,
									), array (
										'$set' =>$set,
										'$inc' => array (
											'count' => 1,
										),
										
									), array (
									'upsert' => true,
								
							));
					 	}
					}
				
				}
			}
			@fclose($handle);
		}
//		print_r($counter);
	}

	public function __destruct() {
				unlink($this->tempFile);
		//		parent :: __destruct();
	}
}